import BasePlugin from './BasePlugin';

/**
 * 背景插件 - 处理画布背景管理
 */
export default class BackgroundPlugin extends BasePlugin {
    constructor() {
        super();
        this.defaultPattern = {
            repeat: 'repeat',
            offsetX: 0,
            offsetY: 0
        };
        this.defaultGradient = {
            type: 'linear',
            coords: {
                x1: 0,
                y1: 0,
                x2: 0,
                y2: 1
            },
            colorStops: [
                { offset: 0, color: '#ffffff' },
                { offset: 1, color: '#000000' }
            ]
        };
    }

    /**
     * 初始化插件
     */
    init(editor) {
        super.init(editor);
        this._setupEventListeners();
    }

    /**
     * 设置背景颜色
     */
    setBackgroundColor(color, options = {}) {
        if (!this.isEnabled() || !this.canvas) return;

        this.canvas.setBackgroundColor(color, () => {
            this.canvas.renderAll();
            this._emitBackgroundEvent('color', { color });
        });
    }

    /**
     * 设置背景图片
     */
    setBackgroundImage(imageUrl, options = {}) {
        if (!this.isEnabled() || !this.canvas) return;

        fabric.Image.fromURL(imageUrl, (img) => {
            const canvasWidth = this.canvas.width;
            const canvasHeight = this.canvas.height;

            // 计算图片缩放比例以适应画布
            let scaleX = 1;
            let scaleY = 1;

            if (options.stretch) {
                scaleX = canvasWidth / img.width;
                scaleY = canvasHeight / img.height;
            } else if (options.fit) {
                const scale = Math.min(
                    canvasWidth / img.width,
                    canvasHeight / img.height
                );
                scaleX = scaleY = scale;
            }

            // 设置背景图片
            this.canvas.setBackgroundImage(img, () => {
                img.set({
                    scaleX: scaleX,
                    scaleY: scaleY,
                    originX: 'left',
                    originY: 'top',
                    left: options.left || 0,
                    top: options.top || 0,
                    opacity: options.opacity || 1
                });

                this.canvas.renderAll();
                this._emitBackgroundEvent('image', { image: img });
            });
        });
    }

    /**
     * 设置背景图案
     */
    setBackgroundPattern(patternUrl, options = {}) {
        if (!this.isEnabled() || !this.canvas) return;

        fabric.util.loadImage(patternUrl, (img) => {
            const pattern = new fabric.Pattern({
                source: img,
                repeat: options.repeat || this.defaultPattern.repeat,
                offsetX: options.offsetX || this.defaultPattern.offsetX,
                offsetY: options.offsetY || this.defaultPattern.offsetY
            });

            this.canvas.setBackgroundColor(pattern, () => {
                this.canvas.renderAll();
                this._emitBackgroundEvent('pattern', { pattern });
            });
        });
    }

    /**
     * 设置背景渐变
     */
    setBackgroundGradient(options = {}) {
        if (!this.isEnabled() || !this.canvas) return;

        const gradientType = options.type || this.defaultGradient.type;
        const coords = { ...this.defaultGradient.coords, ...options.coords };
        const colorStops = options.colorStops || this.defaultGradient.colorStops;

        let gradient;
        if (gradientType === 'linear') {
            gradient = new fabric.Gradient({
                type: 'linear',
                coords: {
                    x1: coords.x1 * this.canvas.width,
                    y1: coords.y1 * this.canvas.height,
                    x2: coords.x2 * this.canvas.width,
                    y2: coords.y2 * this.canvas.height
                },
                colorStops
            });
        } else if (gradientType === 'radial') {
            gradient = new fabric.Gradient({
                type: 'radial',
                coords: {
                    r1: coords.r1 || 0,
                    r2: coords.r2 || this.canvas.width / 2,
                    x1: this.canvas.width / 2,
                    y1: this.canvas.height / 2,
                    x2: this.canvas.width / 2,
                    y2: this.canvas.height / 2
                },
                colorStops
            });
        }

        if (gradient) {
            this.canvas.setBackgroundColor(gradient, () => {
                this.canvas.renderAll();
                this._emitBackgroundEvent('gradient', { gradient });
            });
        }
    }

    /**
     * 清除背景
     */
    clearBackground() {
        if (!this.isEnabled() || !this.canvas) return;

        this.canvas.setBackgroundImage(null, () => {
            this.canvas.setBackgroundColor('', () => {
                this.canvas.renderAll();
                this._emitBackgroundEvent('clear');
            });
        });
    }

    /**
     * 获取背景信息
     */
    getBackgroundInfo() {
        if (!this.canvas) return null;

        return {
            color: this.canvas.backgroundColor,
            image: this.canvas.backgroundImage,
            opacity: this.canvas.backgroundImage ? this.canvas.backgroundImage.opacity : 1
        };
    }

    /**
     * 设置背景不透明度
     */
    setBackgroundOpacity(opacity) {
        if (!this.isEnabled() || !this.canvas) return;

        if (this.canvas.backgroundImage) {
            this.canvas.backgroundImage.set('opacity', opacity);
        }
        this.canvas.renderAll();
        this._emitBackgroundEvent('opacity', { opacity });
    }

    /**
     * 设置背景位置
     */
    setBackgroundPosition(left, top) {
        if (!this.isEnabled() || !this.canvas || !this.canvas.backgroundImage) return;

        this.canvas.backgroundImage.set({
            left: left,
            top: top
        });
        this.canvas.renderAll();
        this._emitBackgroundEvent('position', { left, top });
    }

    /**
     * 设置背景大小
     */
    setBackgroundSize(width, height) {
        if (!this.isEnabled() || !this.canvas || !this.canvas.backgroundImage) return;

        const img = this.canvas.backgroundImage;
        const scaleX = width / img.width;
        const scaleY = height / img.height;

        img.set({
            scaleX: scaleX,
            scaleY: scaleY
        });
        this.canvas.renderAll();
        this._emitBackgroundEvent('size', { width, height });
    }

    /**
     * 发送背景事件
     */
    _emitBackgroundEvent(type, data = null) {
        this.editor.emit('background:' + type, {
            type,
            data
        });
    }

    /**
     * 设置事件监听
     */
    _setupEventListeners() {
        if (!this.canvas) return;

        // 监听画布尺寸变化
        this.canvas.on('resize', () => {
            if (!this.isEnabled()) return;

            const background = this.canvas.backgroundImage;
            if (background) {
                // 调整背景图片大小以适应新的画布尺寸
                this._adjustBackgroundSize(background);
            }
        });
    }

    /**
     * 调整背景图片大小
     */
    _adjustBackgroundSize(background) {
        const canvasWidth = this.canvas.width;
        const canvasHeight = this.canvas.height;
        const imgWidth = background.width;
        const imgHeight = background.height;

        // 计算新的缩放比例
        const scaleX = canvasWidth / imgWidth;
        const scaleY = canvasHeight / imgHeight;

        background.set({
            scaleX: scaleX,
            scaleY: scaleY
        });

        this.canvas.renderAll();
    }

    /**
     * 销毁插件
     */
    destroy() {
        if (this.canvas) {
            this.clearBackground();
        }
        super.destroy();
    }
} 